//
//  TabBarController.m
//  Zhai
//
//  Created by 周文静 on 16/7/28.
//  Copyright © 2016年 lechuangshidai. All rights reserved.
//

#import "TabBarController.h"

@interface TabBarController ()<UITabBarControllerDelegate>

// 记录上次选中的按钮
@property (strong, nonatomic) UIButton *lastBtn;


@end

@implementation TabBarController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 删除系统自带的tabBarButton
    for (UIView *tabBarButton in self.tabBar.subviews) {
        
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            
            [tabBarButton removeFromSuperview];
            
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];

    // 循环添加btn
    CGFloat btnX;
    CGFloat btnY = 0;
    CGFloat btnW = self.view.frame.size.width / 4;
    CGFloat btnH = self.tabBar.frame.size.height;  // 默认49
    for (int i = 0 ; i < 4; i ++) {
        
        // 高亮状态系统默认调用setHighted方法处理图片
        UIButton *btn = [[UIButton alloc]init];
        
        // 1 frame
        btnX = i * btnW;
  
       btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        
        // 2 背景
        NSString *norImageName = [NSString stringWithFormat:@"tabBar-%d",i];
        NSString *higImageName = [NSString stringWithFormat:@"tabBar_hig-%d",i];
        
        // 居中（可以设置图片大小不变）
        [btn setImage:[UIImage imageNamed:norImageName] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:higImageName] forState:UIControlStateSelected];
        
        // 3 监听事件
        [btn addTarget:self action:@selector(tabBarBtnClick:) forControlEvents:UIControlEventTouchDown];
        
        // 4 默认第一个被选中
        if (0 == i) {
            [self tabBarBtnClick:btn];
        }
        
        // 5 tag
        btn.tag = i;
        
        // 6
        btn.adjustsImageWhenHighlighted = NO;
        
        [self.tabBar addSubview:btn];
    }
    
    // 删除系统tabBar
//        [self.tabBar removeFromSuperview];
}


-(void)tabBarBtnClick:(UIButton *)btn
{
    // 把上次选中的btn变成不被选中状态
    self.lastBtn.selected = NO;
    
    // 改变btn的状态为selected
    btn.selected = YES;
    
    // 记录选中的btn
    self.lastBtn = btn;
    
    // 切换控制器
    self.selectedIndex = btn.tag;
   
    
}

@end
